﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;

namespace ApiData.Web.Controllers
{
    [AllowAnonymous]
    public class FileController : BaseController
    {
        private readonly IHostEnvironment env;
        private readonly IMemoryCache cache;

        public FileController(IHostEnvironment env, SqlSugarClient context, IMemoryCache cache) : base(context)
        {
            this.env = env;
            this.cache = cache;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadImage()
        {
            Response.ContentType = "text/html";
            var file = Request.Form.Files[0];
            var names = file.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            var extend = names[^1].ToLower();

            int size = 1 * 1024 * 1024;
            string[] exts = { "png", "jpg", "gif", "jpeg", "bmp" };
            if (file.Length > size) return Content(Result.Fail("图片限制1MB大小").ToJson());
            if (!exts.Any(x => x == extend)) return Content(Result.Fail("图片格式错误").ToJson());

            var path = env.ContentRootPath;
            var virpath = $"/upload/{DateTime.Now:yyyy/MM/dd}/";
            var newname = Guid.NewGuid().ToString("N") + "." + extend;
            if (!Directory.Exists(path + virpath))
            {
                Directory.CreateDirectory(path + virpath);
            }

            FileStream stream = new FileStream(path + virpath + newname, FileMode.Create);
            file.CopyTo(stream);
            stream.Dispose();

            return Content(Result.SuccessData(virpath + newname).ToJson());
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upload()
        {
            Response.ContentType = "text/html";
            var file = Request.Form.Files[0];
            var names = file.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            var extend = names[^1].ToLower();

            int size = 5 * 1024 * 1024;
            if (file.Length > size) return Content(Result.Fail("文件限制5MB大小").ToJson());

            var path = env.ContentRootPath;
            var virpath = $"/upload/{DateTime.Now:yyyy/MM/dd}/";
            var newname = Guid.NewGuid().ToString("N") + "." + extend;
            if (!Directory.Exists(path + virpath))
            {
                Directory.CreateDirectory(path + virpath);
            }

            FileStream stream = new FileStream(path + virpath + newname, FileMode.Create);
            file.CopyTo(stream);
            stream.Dispose();

            return Content(Result.SuccessData(virpath + newname).ToJson());
        }
        /// <summary>
        /// UEditor插件上传
        /// </summary>
        /// <returns></returns>
        public IActionResult EditorUpload()
        {
            Response.ContentType = "text/html";
            var file = Request.Form.Files[0];
            var names = file.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            var extend = names[^1].ToLower();

            int size = 1 * 1024 * 1024;
            string[] exts = { "jpg", "jpeg", "png", "gif", "bmp", "exe", "flv", "swf", "mkv", "avi",
                "rm", "rmvb", "mpeg", "mpg", "ogg", "ogv", "mov", "wmv", "mp4", "webm", "mp3", "wav",
                "mid", "rar", "zip", "tar", "gz", "7z", "bz2", "cab", "iso", "chm", "doc", "docx",
                "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "md", "xml", "torrent" };
            if (file.Length > size) return Json(new
            {
                url = "",
                name = "",
                error = "文件限制1MB大小"
            });
            if (!exts.Any(x => x == extend)) return Json(new
            {
                url = "",
                name = "",
                error = "图片格式错误"
            });

            var path = env.ContentRootPath;
            var virpath = $"/upload/{DateTime.Now:yyyy/MM/dd}/";
            var newname = Guid.NewGuid().ToString("N") + "." + extend;
            if (!Directory.Exists(path + virpath))
            {
                Directory.CreateDirectory(path + virpath);
            }

            FileStream stream = new FileStream(path + virpath + newname, FileMode.Create);
            file.CopyTo(stream);
            stream.Dispose();

            return Json(new
            {
                url = virpath + newname,
                name = newname,
                error = 0
            });
        }
    }
}
